﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SharpLite.Domain.DataInterfaces;
using DAEProde.Domain;
using DAEProde.Tasks;

namespace DAEProde.Web.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class MatchManagerController : Controller
    {
        private IRepository<Match> _matchRepository;
        private IRepository<MatchDate> _matchDateRepository;
        private MatchCudTasks _matchMgmtTasks;

        public MatchManagerController(IRepository<Match> matchRepository, IRepository<MatchDate> matchDateRepository, MatchCudTasks matchMgmtTasks)
        {
            _matchRepository = matchRepository;
            _matchDateRepository = matchDateRepository;
            _matchMgmtTasks = matchMgmtTasks;
        }

        //
        // GET: /MatchManager

        public ActionResult Index(int id)
        {
            return View(_matchDateRepository.Get(id));
        }

        public ActionResult Create(int id)
        {
            return View("Edit", _matchMgmtTasks.CreateViewModel(id));
        }

        public ActionResult Details(int id)
        {
            return View(_matchRepository.Get(id));
        }

        public ActionResult Edit(int id)
        {
            return View(_matchMgmtTasks.CreateEditViewModel(id));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Match match)
        {
            if (ModelState.IsValid)
            {
                if (match.LocalTeam.Equals(match.OutTeam))
                {
                    TempData["message"] = "El equipo local debe ser diferente del equipo visitante";
                }
                else
                {
                    match.Result = "Sin Cargar";
                    ActionConfirmation<Match> confirmation = _matchMgmtTasks.SaveOrUpdate(match);

                    if (confirmation.WasSuccessful)
                    {
                        TempData["message"] = confirmation.Message;
                        return RedirectToAction("Index", new { id = match.MatchDate.Id });
                    }

                    ViewData["message"] = confirmation.Message;
                }
            }

            return View(_matchMgmtTasks.CreateEditViewModel(match));
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            var aa = _matchDateRepository.GetAll();
            
            var tmpId = _matchRepository.Get(id).MatchDate.Id;

            ActionConfirmation<Match> confirmation = _matchMgmtTasks.Delete(id);
            TempData["message"] = confirmation.Message;

            return RedirectToAction("Index", new { id = tmpId });
        }
    }
}
